package cn.mumzone.pos.ui.fragment;

import android.support.v7.widget.AppCompatImageView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.ruffian.library.widget.RImageView;
import com.ruffian.library.widget.RTextView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.mumzone.basic.base.BaseFragment;
import cn.mumzone.basic.util.AppDateUtil;
import cn.mumzone.basic.util.BigDecimalUtil;
import cn.mumzone.basic.util.DisplayUtil;
import cn.mumzone.basic.util.PosToast;
import cn.mumzone.pos.AppConstants;
import cn.mumzone.pos.R;
import cn.mumzone.pos.model.ReserveEntity;
import cn.mumzone.pos.model.ServerEntity;
import cn.mumzone.pos.model.ServerTimeTableEntity;
import cn.mumzone.pos.presenter.ServerTimeTablePresenter;
import cn.mumzone.pos.presenter.contract.ServerTimeTableContract;
import cn.mumzone.pos.ui.activity.ACT_Schedule;
import cn.mumzone.pos.ui.adapter.ADA_ReserveInfo;
import cn.mumzone.pos.ui.widgets.ScrollablePanel;
import cn.mumzone.pos.util.AppUtil;
import cn.mumzone.pos.util.PopupUtil;

/**
 * Created by qiuzhenhuan on 2019/6/19.
 */

public class FRA_ServerTimeTable extends BaseFragment<ServerTimeTablePresenter> implements ServerTimeTableContract.View {

    @BindView(R.id.sp_reserve_info)
    ScrollablePanel spReserveInfo;
    @BindView(R.id.tv_day)
    TextView tvDay;
    @BindView(R.id.ic_go_previous_day)
    AppCompatImageView icGoPreviousDay;
    @BindView(R.id.ic_go_next_day)
    AppCompatImageView icGoNextDay;
    Unbinder unbinder;
    @BindView(R.id.rtv_jump_schedule)
    RTextView rtvJumpSchedule;
    @BindView(R.id.ll_empty_layout)
    LinearLayout llEmptyLayout;
    @BindView(R.id.tv_reserve)
    TextView tvReserve;
    @BindView(R.id.tv_service)
    TextView tvService;
    @BindView(R.id.iv_refresh)
    AppCompatImageView ivRefresh;
    @BindView(R.id.riv_news_tip)
    RImageView rivNewsTip;
    @BindView(R.id.ll_tips_layout)
    LinearLayout tipsLayout;
    @BindView(R.id.tv_empty_hint)
    TextView tvEmptyHint;
    @BindView(R.id.iv_empty_pic)
    ImageView ivEmptyPic;
    private List<ServerTimeTableEntity.ShopBusinessHoursBean> businessHoursList;
    ADA_ReserveInfo adapter;

    private int currentDatePosition = 0;
    private List<String> dateStrList = new ArrayList<>();

    private PopupWindow mPopUp;

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (hidden) {
            if (mPopUp != null) {
                mPopUp.dismiss();
                mPopUp = null;
            }
        }
    }

    @Override
    protected void initEventAndData() {

        adapter = new ADA_ReserveInfo(mContext);
        spReserveInfo.setPanelAdapter(adapter);
        initDate();
        mPresenter.addNewsTipsListener();
        mPresenter.getSeverTimeTable(AppDateUtil.getTimeStamp(new Date(), AppDateUtil.YYYY_MM_DD_HH_MM_SS),
                AppUtil.hasServiceBusiness() ? "1" : "2");

        showPopupHint();

        isPopupHintPrepared = true;

//        ArrayList<ServerEntity> serverList = new ArrayList<>();
//        for (int i = 0; i < 12; i++) {
//            serverList.add(new ServerEntity());
//        }
//        adapter.setServerList(serverList);
//
//
//        ArrayList<ServerTimeTableEntity.ShopBusinessHoursBean> timeList = new ArrayList<>();
//        for (int i = 7; i <= 22; i++) {
//            ServerTimeTableEntity.ShopBusinessHoursBean entity1 = new ServerTimeTableEntity.ShopBusinessHoursBean();
//            ServerTimeTableEntity.ShopBusinessHoursBean entity2 = new ServerTimeTableEntity.ShopBusinessHoursBean();
//            entity1.setMinuteName(String.format("%s:00", i));
//            entity2.setMinuteName(String.format("%s:30", i));
//            timeList.add(entity1);
//            timeList.add(entity2);
//        }
//        adapter.setTimeList(timeList);
//
//        List<ReserveEntity> testList = getReserveList();
//        Random random = new Random(3);
//
//        List<List<ReserveEntity>> reserveList = new ArrayList<>();
//        for (int i = 0; i < 12; i++) {
//            List<ReserveEntity> orderList = new ArrayList<>();
//            for (int j = 0; j < timeList.size(); j++) {
//                orderList.add(testList.get(random.nextInt(4)));
//            }
//            reserveList.add(orderList);
//        }
//        adapter.setReserveList(reserveList);


    }

    private void initDate() {
        for (int i = 0; i < 7; i++) {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DAY_OF_MONTH, i);
            String str = AppDateUtil.getTimeStamp(calendar.getTime().getTime(), AppDateUtil.YYYY_MM_DD1) + " " +
                    AppDateUtil.getWeekOfDate(calendar.getTime().getTime());
            dateStrList.add(str);
        }
        tvDay.setText(dateStrList.get(currentDatePosition));
    }

    public int getPassTimeWidth(String time) {
        int maxWidth = DisplayUtil.dip2px(mContext, 153);
        long nowTime = System.currentTimeMillis();
        String nowDay = AppDateUtil.getTimeStamp(nowTime, AppDateUtil.YYYY_MM_DD);
        long currentTime = AppDateUtil.getStringToDate(String.format("%s %s", nowDay, time), AppDateUtil.YYYY_MM_DD_HH_MM);
        long diffTime = nowTime - currentTime;
        double scale = BigDecimalUtil.div(String.valueOf(diffTime), String.valueOf(60 * 1000 * 30));
        return (int) (maxWidth * scale);
    }


    public List<ReserveEntity> getReserveList() {
        List<ReserveEntity> orderList = new ArrayList<>();
        ReserveEntity entity = new ReserveEntity();
        entity.setStatus(ReserveEntity.STATUS_BLANK);
        entity.setServiceName("宝贝单次游泳抚触");
        entity.setServiceTime("8:30-9:00");
        entity.setId("1");
        orderList.add(entity);

        ReserveEntity entity2 = new ReserveEntity();
        entity2.setStatus(ReserveEntity.STATUS_BLANK);
        entity2.setServiceName("宝贝游泳抚触");
        entity2.setServiceTime("7:30-9:00");
        entity2.setId("2");
        orderList.add(entity2);

        ReserveEntity entity3 = new ReserveEntity();
        entity3.setStatus(ReserveEntity.STATUS_RESERVE);
        entity3.setServiceName("宝贝单次游泳抚触");
        entity3.setServiceTime("8:30-9:00");
        entity3.setId("1");
        orderList.add(entity3);

        ReserveEntity entity4 = new ReserveEntity();
        entity4.setStatus(ReserveEntity.STATUS_SERVICE);
        entity4.setServiceName("宝贝游泳抚触");
        entity4.setServiceTime("7:30-9:00");
        entity4.setId("2");
        orderList.add(entity4);

        return orderList;

    }

    @Override
    protected void onUserVisible() {
        initDate();
        currentDatePosition = 0;
        tvDay.setText(dateStrList.get(currentDatePosition));
        mPresenter.getSeverTimeTable(AppDateUtil.getTimeStamp(new Date(), AppDateUtil.YYYY_MM_DD_HH_MM_SS),
                AppUtil.hasServiceBusiness() ? "1" : "2");
    }

    @Override
    protected int getLayout() {
        return R.layout.fra_reserve;
    }

    @Override
    public void onServerTimeTableReceived(ServerTimeTableEntity entity) {

        if (spReserveInfo.getVisibility() != View.VISIBLE) {
            setViewVisibility(spReserveInfo, true);
            setViewVisibility(llEmptyLayout, false);
        }
        tvReserve.setText("已预约(" + entity.getAppointmentSum() + ")");
        tvService.setText("服务中(" + entity.getServiceSum() + ")");
        businessHoursList = entity.getShopBusinessHours();
        List<List<ReserveEntity>> serverTimeTableList = new ArrayList<>();
        List<ServerEntity> serverList = new ArrayList<>();

        for (int i = 0; i < entity.getTechnicianList().size(); i++) {

            ServerTimeTableEntity.TechnicianListBean technicianListBean = entity.getTechnicianList().get(i);
            List<ReserveEntity> singleServerTimeList = new ArrayList<>();

            for (int innerCount = 0; innerCount < technicianListBean.getTimeList().size(); innerCount++) {

                ServerTimeTableEntity.TechnicianListBean.TimeListBean bean = technicianListBean.getTimeList().get(innerCount);

                singleServerTimeList.add(new ReserveEntity(
                        Integer.parseInt(bean.getServiceStatus()),
                        bean.getServiceId(),
                        technicianListBean.getTimeList().get(innerCount).getServiceName(),
                        bean.getStartTime() + "-" + bean.getEndTime(),
                        technicianListBean.getTechnicianName(),
                        technicianListBean.getTechnicianId(),
                        bean.getOrderSubId(),
                        bean.getAppointmentId(),
                        bean.getAppointmentType(),
                        bean.getStartTime(),
                        bean.getEndTime()));
            }
            serverTimeTableList.add(singleServerTimeList);
            serverList.add(new ServerEntity(technicianListBean.getTechnicianName(), technicianListBean.getTechnicianLabel(), technicianListBean.getServiceCount()));
        }
        adapter.setIsToday(currentDatePosition == 0);
        adapter.setDaysPosition(currentDatePosition);
        adapter.setServerList(serverList);
        adapter.setTimeList(businessHoursList);
        adapter.setReserveList(serverTimeTableList);
        spReserveInfo.notifyDataSetChanged();

    }

    @Override
    public void showToast(String content) {

    }

    @Override
    public void showEmpty(boolean scheduleOrTechnician) {
        setViewVisibility(spReserveInfo, false);
        setViewVisibility(llEmptyLayout, true);
        rtvJumpSchedule.setVisibility(scheduleOrTechnician ? View.VISIBLE : View.GONE);
        tvEmptyHint.setText(scheduleOrTechnician ? "您还没有排班哦~" : "您还没有添加技师哦~");

    }

    @Override
    public void showNews() {
        setViewVisibility(rivNewsTip, true);
    }

    @Override
    public void hideNewsTip() {
        setViewVisibility(rivNewsTip, false);
    }

    private void getTimeParams() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, currentDatePosition);
        mPresenter.getSeverTimeTable(currentDatePosition == 0 ? AppDateUtil.getTimeStamp(calendar.getTime(), AppDateUtil.YYYY_MM_DD_HH_MM_SS) :
                        AppDateUtil.getTimeStamp(calendar.getTime(), AppDateUtil.YYYY_MM_DD) + " 23:59:59",
                AppUtil.hasServiceBusiness() ? "1" : "2");
    }


    @OnClick({R.id.ic_go_previous_day, R.id.ic_go_next_day, R.id.rtv_jump_schedule, R.id.iv_refresh, R.id.ll_tips_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ic_go_previous_day:
                if (currentDatePosition >= 1) {
                    currentDatePosition--;
                    tvDay.setText(dateStrList.get(currentDatePosition));
//                    Calendar calendar = Calendar.getInstance();
//                    calendar.add(Calendar.DAY_OF_MONTH, currentDatePosition);
//                    mPresenter.getSeverTimeTable(AppDateUtil.getTimeStamp(calendar.getTime(), AppDateUtil.YYYY_MM_DD_HH_MM_SS),
//                            AppConstants.BUSINESS_SCOPE_SERVICE.equals(AppConstants.TEMP_BUSINESS_SCOPE) ? "1" : "2");
                    getTimeParams();
                } else {
                    PosToast.INSTANCE.makeShortToast(mContext, "已经是今天了！");
                }
                break;
            case R.id.ic_go_next_day:
                if (currentDatePosition < 6) {
                    currentDatePosition++;
                    tvDay.setText(dateStrList.get(currentDatePosition));
                    getTimeParams();
                } else {
                    PosToast.INSTANCE.makeShortToast(mContext, "最多只能查看7天数据");
                }
                break;
            case R.id.rtv_jump_schedule:
                if (AppConstants.TEMP_USER_PERMISSION != null && AppConstants.TEMP_USER_PERMISSION.isScheduling()) {
                    ACT_Schedule.startAc(mContext);
                } else {
                    PosToast.INSTANCE.makeShortToast(mContext, "无排班权限");
                }
                break;
            case R.id.iv_refresh:
                PopupUtil.dismissPopup(PopupUtil.TIME_TABLE_REFRESH, mPopUp);
                getTimeParams();
                break;
            case R.id.ll_tips_layout:
                break;
        }
    }

    @Override
    public void showError(String msg) {
        PosToast.INSTANCE.makeToast(mContext, PosToast.ToastType.TOAST_TYPE_RECTANGLE, PosToast.ToastRectangleLevel.ALERT_WARNING_LEVEL_ONE, msg, false);
    }

    @Override
    public void showNetError() {
        PosToast.INSTANCE.makeShortToast(mContext, "网络不给力，请稍后再试");
    }

    @Override
    protected boolean hasViewPermission() {
        return AppConstants.TEMP_USER_PERMISSION != null && AppConstants.TEMP_USER_PERMISSION.isAppointment();
    }

    public void showPopupHint() {
        ivRefresh.post(new Runnable() {
            @Override
            public void run() {
                mPopUp = PopupUtil.showBlackBgPopup(ivRefresh, PopupUtil.TIME_TABLE_REFRESH, "您有新的订单，点击刷新", PopupUtil.LEFT_TOP);
            }
        });
    }

    @Override
    public boolean hasPopupHint() {
        return true;
    }

    @Override
    public void hidePopupHint() {
        if (mPopUp != null) {
            mPopUp.dismiss();
            mPopUp = null;
        }
    }

}
